package com.changil.nowonchangilchurch.widget.asyncimagegetter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;

public class HttpImageRequester {
	
	HttpImageTask http;
	
	public void request(String url, HttpImageCallback callback) {
		http = new HttpImageTask(url, callback);
		http.execute();
	}
	
	public void cancel() {
		if(http != null)
			http.cancel(true);
	}

	private class HttpImageTask extends AsyncTask<Void, Void, Bitmap> {
		String url;
		HttpImageCallback callback;
		
		public HttpImageTask(String url, HttpImageCallback callback) {
			this.url = url;
			this.callback = callback;
		}
		
		@Override
		protected Bitmap doInBackground(Void... nothing) {
			return fetchDrawable(url);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			this.callback.onResult(result);
		}
		
		 /***
         * Get the Bitmap from URL
         * @param urlString
         * @return
         */
        public Bitmap fetchDrawable(String urlString) {
            try {
                InputStream is = fetch(urlString);
                Bitmap result = BitmapFactory.decodeStream(is);
                return result;
            } catch (Exception e) {
                return null;
            } 
        }

        private InputStream fetch(String urlString) throws MalformedURLException, IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);
            HttpResponse response = httpClient.execute(request);
            return response.getEntity().getContent();
        }
	}
}
